package com.kefu.core.pub;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

public abstract class DefAioHandlerService implements ServerAioHandler {

	/**
	 * 解码
	 */
	public DefPacket decode(ByteBuffer buffer, ChannelContext channelContext)
			throws AioDecodeException {
		List<Byte> bt=new ArrayList<Byte>();//去除数据包空格
		for(byte b:buffer.array()){
			if(b!=0)bt.add(b);
			else break;
		}
		byte[] bs=new byte[bt.size()];
		for(int n=0;n<bs.length;n++){
			bs[n]=bt.get(n);
		}
		buffer=ByteBuffer.wrap(bs);
		int readableLength = buffer.limit() - buffer.position();
		// 收到的数据组不了业务包，则返回null以告诉框架数据不够
		if (readableLength < DefPacket.HEADER_LENGHT) {
			return null;
		}
		// 读取消息体的长度
		int bodyLength = buffer.getInt();
		// 数据不正确，则抛出AioDecodeException异常
		if (bodyLength < 0) {
			throw new AioDecodeException("bodyLength [" + bodyLength
					+ "] is not right, remote:"
					+ channelContext.getClientNode());
		}

		// 计算本次需要的数据长度
		int neededLength = DefPacket.HEADER_LENGHT + bodyLength;
		// 收到的数据是否足够组包
		int isDataEnough = readableLength - neededLength;
		// 不够消息体长度(剩下的buffe组不了消息体)
		if (isDataEnough < 0) {
			return null;
		} else {// 组包成功
			DefPacket imPacket = new DefPacket();
			if (bodyLength > 0) {
				byte[] dst = new byte[bodyLength];
				buffer.get(dst);
				imPacket.setBody(dst);
			}
			return imPacket;
		}
	}

	/**
	 * 编码
	 */
	public ByteBuffer encode(Packet packet, GroupContext groupContext,
			ChannelContext channelContext) {
		System.out.println("111111111111111");
		DefPacket imPacket = (DefPacket) packet;
		byte[] body = imPacket.getBody();
		int bodyLen = 0;
		if (body != null) {
			bodyLen = body.length;
		}
		//bytebuffer的总长度是 = 消息头的长度 + 消息体的长度
		int allLen = DefPacket.HEADER_LENGHT + bodyLen;
		//创建一个新的bytebuffer
		ByteBuffer buffer = ByteBuffer.allocate(allLen);
		//设置字节序
		buffer.order(groupContext.getByteOrder());
		//写入消息头----消息头的内容就是消息体的长度
		buffer.putInt(bodyLen);

		//写入消息体
		if (body != null) {
			buffer.put(body);
		}
		return buffer;
	}
	
}
